import { _decorator, Component, error, Node } from 'cc';
import { ModuleBase } from './ModuleBase';
const { ccclass, property } = _decorator;

@ccclass('ModuleMgr')
export class ModuleMgr{
    private _mapModule:Map<string,ModuleBase>=new Map();
    get mapModule(){
        return this._mapModule;
    }
    private static _instance:ModuleMgr=null;
    static get instance(){
        if(!this._instance){
            this._instance=new ModuleMgr;
        }
        return this._instance;
    }
    constructor(){

    }
    addModuel(modelName:string,module:ModuleBase){
        if(modelName.length <=0||!module){
            return;
        }
        this._mapModule.set(modelName,module);
    }
    getModuel<T>(modelName:string):T{
        if(modelName.length <=0){
            return;
        }
        return this._mapModule.get(modelName) as T;
    }
    deleteModuel(modelName:string){
        if(modelName.length <=0){
            return;
        }
        this._mapModule.delete(modelName);
    }
    clearModule(){
        this._mapModule.clear();
    }
    destroyInstance(){
        ModuleMgr._instance = null;
    }
    OnInitModuel(...rest:any[]){
        for(let value of Array.from(this._mapModule.values())){
            value.onInit.apply(value,arguments);
        }
    }
    OnLateInitModuel(...rest:any[]){
        for(let value of Array.from(this._mapModule.values())){
            value.onLateInit.apply(value,arguments);
        }
    }
    OnUpdateModuel(dt:number,...rest:any[]){
        for(let value of Array.from(this._mapModule.values())){
            value.onUpdate.apply(value,arguments); 
        }
    }
    OnLateUpdateModuel(dt:number,...rest:any[]){
        for(let value of Array.from(this._mapModule.values())){
            value.onLateUpdate.apply(value,arguments); 
        }
    }
    SendMsg(msg:string,modelName?:string,...rest:any[]){
        if(modelName.length<=0||!modelName){
            for(let value of Array.from(this._mapModule.values())){
                let cb =value[msg];
                if(cb){
                    cb.apply(value,rest);
                    continue;
                }
                value.handleMsg(value,rest);

            }
            return;
        }
        if(!this._mapModule.get(modelName)){
            error("未找到该模块"+this._mapModule.get(modelName))
            return;
        }
        let cb=this._mapModule.get(modelName)[msg];
        cb.apply(this._mapModule.get(modelName),rest);
    }
}


